import { URL } from 'url'
import uuid from 'node-uuid'

import router from './_'

/**
 * 用户验证码
 */
router.put('/user/check_code', async (ctx, next) => {
  ctx.body = {
    code: '1234',
  }
})

/**
 * 用户注册
 */
router.post('/singup', async (ctx, next) => {
  const User = ctx.db.User
  const body = ctx.request.body
  // 验证码
  if (!body.code || body.code.toString() !== '1234') {
    ctx.status = 422
    return ctx.body = {
      message: '验证码错误！',
    }
  }
  // 是否存在
  const _user = await User.findOne({ username: body.username }, { _id: 1 })
  if (_user) {
    ctx.status = 422
    return ctx.body = {
      message: '用户名已存在',
    }
  }
  body.password = ctx.encrypt(body.password)
  const user = await User.create(body)
  user.password = null
  ctx.body = user
})

/**
 * 用户登录
 */
router.post('/login', async (ctx, next) => {
  const User = ctx.db.User
  const body = ctx.request.body
  const query = ctx.request.query
  const app = await ctx.db.App.findOne({ code: query.code })
  if (query.code && (!app || !query.address)) {
    ctx.status = 422
    return ctx.body = {
      message: '应用ID无效！',
    }
  }
  // 验证码
  if (!body.code || body.code.toString() !== '1234') {
    ctx.status = 422
    return ctx.body = {
      message: '验证码错误！',
    }
  }
  let user = await User.findOne({ username: body.username })
                       .populate('school', { name: 1 })
  if (!user) {
    ctx.status = 404
    return ctx.body = {
      message: '用户不存在',
    }
  }
  if (user.password !== ctx.encrypt(body.password)) {
    ctx.status = 403
    return ctx.body = {
      message: '密码错误',
    }
  }
  if (user.state === 5) {
    ctx.status = 403
    return ctx.body = {
      message: '用户已被禁止登陆！',
    }
  }
  // 记录IP地址
  user.lastLogin = ctx.header['X-Real-IP'] || ctx.request.ip
  user = await user.save()
  user.password = `${user._id}_${uuid.v1()}`
  // Token
  ctx.db.redisClient.setSync(user._id.toString(), JSON.stringify(user), 'EX', body.remember ? 3600 * 30 : 3600 * 7)
  if (query.code) {
    const url = new URL(query.address)
    url.searchParams.set('token', user.password)
    ctx.redirect(url.toString())
  } else {
    ctx.body = user
  }
})

router.get('/login', async (ctx, next) => {
  const query = ctx.request.query
  const App = ctx.db.App
  let app = await App.findOne({ code: query.code })
  if (!app) {
    ctx.status = 404
    return ctx.body = {
      message: '应用不存在',
    }
  }
  if (!query.address.includes(app.address)) {
    ctx.status = 422
    return ctx.body = {
      message: '回调地址错误！',
    }
  }
  ctx.body = app
})

/**
 * 更新信息
 */
router.put('/user/:id', async (ctx, next) => {
  ctx.body = {}
})

/**
 * 注销登录
 */
router.delete('/user/:id', async (ctx, next) => {
  ctx.body = {}
})

export default router